// Random integer between min <= random <= max
function rand(min, max) {
  return min + Math.floor((1 + max - min) * Math.random());
}

// Random float min <= random < max
function randFloat(min, max) {
  return min + ((max - min) * Math.random());
}

// Get random element from array with probablitity
// items ["item 1", "item 2", ... , "item n"]
// prbabilities = [ 0.1, 0.2, ] (Sum has to be 1)
getRandomItem = function(items, probabilities) {
  
  if(items.length != probabilities.length) {
    console.log("Error in getRandomItem. Vectors are not equaly long.");
  }
  
  var sumProb = 0;
  for (var i = 0; i <probabilities.length; i++) {
    sumProb += probabilities[i];
  }
  
  if (sumProb != 1) {
    console.log("Error in getRanodomItem. Probabilities do not sum up to 1.")
    return items[0];
  }
  
  var randValue = randFloat(0,1);
  var tmpProb = 0;
  for (var i = 0; i < items.length; i++) {
    tmpProb += probabilities[i];
    if ( randValue < tmpProb) {
      return items[i];
    }
  }
  
}

// Returns true or fals with a certain probability (0-1)
function zeroOrOne(probability) {
  return rand(0, 999) < (probability * 1000);
}


function distance(x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;
  return Math.sqrt((dx * dx) + (dy * dy));
}

// angle from 12 to point, counterclockwise (really?)
function angle(x1, y1, x2, y2) {
  return Math.atan2(x1 - x2, y2 - y1) * 57.29578;
}


// Checks if point is inside polygon, polygon is array with x,y coordinates
function inPolygon(polygon, pointX, pointY) {
  var inside = false;
  var j = (polygon.length - 1);
  for(var i = 0; i < polygon.length; i++) {
    if(((polygon[i].y > pointY) != (polygon[j].y > pointY)) &&
        (pointX < (polygon[j].x - polygon[i].x) * (pointY - polygon[i].y) / (polygon[j].y - polygon[i].y) + polygon[i].x)) {
      inside = !inside;
    }
    j = i;
  }
  return inside;
}

// vector has form {x : 1, y : 2}
function normalize(vector) {
  var length = Math.sqrt((vector.x * vector.x) + (vector.y * vector.y));
  if(length == 0) {
    return { x : 0, y : 0 };
  }
  return { x : (vector.x / length), y : (vector.y / length) };
}

// Returns a the first maching value for value in the range [min, max], 
function setInRange(value, min, max) {
  if(value < min) {
    return min;
  }
  if(value > max) {
    return max;
  }
  return value;
}


function drawEllipse(c, x, y, w, h) {
  var kappa = 0.5522848;
  var ox = (w / 2) * kappa;
  var oy = (h / 2) * kappa;
  var xe = x + w;
  var ye = y + h;
  var xm = x + w / 2;
  var ym = y + h / 2;

  c.beginPath();
  c.moveTo(x, ym);
  c.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  c.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  c.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  c.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  c.closePath();
  c.stroke();
}